package com.sgb.member.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberInviteJoinBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.CompanyDeptBean;
import com.sgb.member.entity.MInviteEntity;
import com.sgb.member.entity.MemberApprovalBean;
import com.sgb.member.entity.MemberProfileBean;
import com.sgb.member.entity.ParamDtosEntity;
import com.sgb.member.entity.ProcessBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.entity.ThresholdParamBean;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MemberEvent;
import com.sgb.member.ui.adapter.MemberJoinThresholdAdapter;
import com.sgb.member.view_model.MInviteJoinModel;
import com.sgb.member.weight.AppendFieldsView;
import com.sgb.member.weight.NumberInputFilter;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.UploadFileBean;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.DisplayUtil;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 邀请加盟
 * isAgainInvite true eg :
 * {
 * "id": 1777,ResolutionUtil
 * "no": "5ff6acc2e4b03cb012737728",
 * "name": "心相印",
 * "memberRelation": 1,
 * "memberRelationName": "供方会员",
 * "companyNo": "202011305158388",
 * "companyId": "137280",
 * "serviceType": "56",
 * "serviceTypeName": "专业承包企业",
 * "addr": "新疆维吾尔自治区乌鲁木齐市天山区",
 * "status": "1",
 * "processId": null,
 * "createTime": "2021-01-07 14:40",
 * "createTimeStr": null,
 * "updateTime": "2021-01-07 14:40:02",
 * "firstCategoryNo": "138661966820632583
 * "secondCategoryNo": null,
 * "thirdCategoryNo": null,
 * "fourCategoryNo": null,
 * "fiveCategoryNo": null,
 * "firstCategory": [],
 * "secondCategory": [],
 * "thirdCategory": [],
 * "fourCategory": [],
 * "fiveCategory": [],
 * "allCategory": []
 * }
 */
public class MemberInviteJoinActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    @Inject
    MInviteJoinModel sModel;
    private ActivityMemberInviteJoinBinding mBinding;

    private QualityMemberBean qualityMemberBean;
    private boolean isAgainInvite; // 是否再次邀请
    private boolean isJumpFromWeb;

    private MInviteEntity mJoinEntity; // 邀请加盟
    private MemberApprovalBean mApprovalBean;  // 邀请加盟审批

    // 会员门槛类型保存
    private List<CommonPopEntity> mAppealCateList = new ArrayList<>();

    public static void start(Activity context, QualityMemberBean bean) {
        Intent intent = new Intent(context, MemberInviteJoinActivity.class);
        intent.putExtra("OBJECT", (Serializable) bean);
        context.startActivityForResult(intent, MemberConfig.REQ_SERVICE);
    }

    public static void startAgain(Activity context, QualityMemberBean bean, boolean isWeb) {
        Intent intent = new Intent(context, MemberInviteJoinActivity.class);
        intent.putExtra("OBJECT", (Serializable) bean);
        intent.putExtra("AGAIN", true); // 是否再次申请
        intent.putExtra("IS_WEB", isWeb); // 是否从web 跳转过来
        context.startActivityForResult(intent, MemberConfig.REQ_SERVICE);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        qualityMemberBean = (QualityMemberBean) getIntent().getSerializableExtra("OBJECT");
        isAgainInvite = getIntent().getBooleanExtra("AGAIN", false);
        isJumpFromWeb = getIntent().getBooleanExtra("IS_WEB", false);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_invite_join);
        mBinding.setViewModel(qualityMemberBean);
        mBinding.activityBar.titleView.setText("邀请加盟");
        mBinding.activityBar.rightView.setVisibility(View.INVISIBLE);
        mBinding.activityBar.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        initViewStyle();
        // 设置企业信息
        initEntityInfo();
        // 获取审批流程状态
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        sModel.getProcessStatus(companyNo, "inviteJoinCompany");
    }

    private void initViewStyle() {
        int childCount = mBinding.nestedScrollLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = mBinding.nestedScrollLayout.getChildAt(i);
            if (childView instanceof ItemInputTextView) {
                ((ItemInputTextView) childView).setMemberStyle();
            } else if (childView instanceof CfkEditView) {
                setCfkEditViewStyle((CfkEditView) childView);
            }
        }
        mBinding.itemLever.setOnWholeItemClickListener(this);
        mBinding.itemRelation.setOnWholeItemClickListener(this);
        mBinding.itemType.setOnWholeItemClickListener(this);
        mBinding.itemType2.setOnWholeItemClickListener(this);
        mBinding.itemApprovalDepartment.setOnWholeItemClickListener(this);

        mBinding.itemContacts.setInfilterType(ItemInputTextView.TYPE_TEXT);
        mBinding.itemContactsPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        mBinding.itemContactsPhone.setMaxSize(11);
        mBinding.itemCooperationExpected.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemMemberRequirements.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mBinding.itemCooperationExpected.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});
        mBinding.itemMemberRequirements.setFilters(new NumberInputFilter[]{new NumberInputFilter(99999999999.99, 0.01, 2)});

        mBinding.submit.setOnClickListener(this);
        mBinding.successLayout.tvRecord.setOnClickListener(this);
        mBinding.successLayout.tvFinish.setOnClickListener(this);
        // 默认普通会员
        mBinding.itemLever.setContent("普通会员");
        //默认供方会员 供需关系  1供方  2需方
        mBinding.itemRelation.setContent("供方会员");
        mBinding.tvTopCompany.setText(qualityMemberBean.getCompanyName());
        mBinding.tvTopCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ClickUtils.isDoubleClick()) {
                    MemberConfig.getInstance().startWebsiteInfo(getActivity(), qualityMemberBean.getCompanyNo(), 1);
                }
            }
        });
    }

    // 获取会员审批状态，是否展示审批填写信息
    public void updateProcessStatus(String status) {
        // "status": "1" //1 表示有审批 0 代表无审批
        boolean hasProcess = TextUtils.equals("1", status); // 有流程
        mBinding.approvalLayout.setVisibility(hasProcess ? View.VISIBLE : View.GONE);
        sModel.getCompanyProfile(qualityMemberBean.getCompanyNo());
    }

    /**
     * 初始化获取企业信息
     */
    private void initEntityInfo() {
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String userName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        String userPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        mJoinEntity = new MInviteEntity();
        mJoinEntity.setNo("");
        mJoinEntity.setRelation("1"); //供需关系  1供方  2需方
        mJoinEntity.setLevel("普通会员");
        mJoinEntity.setApplyCompanyNo(qualityMemberBean.getCompanyNo());
        mJoinEntity.setApplyCompanyName(qualityMemberBean.getCompanyName());
        mJoinEntity.setJoinWay("2"); //加盟方式  1申请 2邀请
        mJoinEntity.setCompanyNo(companyNo);
        mJoinEntity.setCompanyName(companyName);
        mJoinEntity.setContacts(userName);
        mJoinEntity.setPhone(userPhone);
        mJoinEntity.setCompanyBusinessOwner(userName);

        mApprovalBean = new MemberApprovalBean();
        mApprovalBean.setNo("");
        // 申请人信息
        mApprovalBean.setApproveType("2"); // 审批类型 1 申请加盟 2邀请加盟
        mApprovalBean.setApplyUserName(userName);
        mApprovalBean.setApplyUserNo(userNo);
        mApprovalBean.setApplyCompanyName(companyName);
        mApprovalBean.setApplyCompanyNo(companyNo);
        mApprovalBean.setDetail("");
        mApprovalBean.setApplyDeptNo("");
        mApprovalBean.setApplyDeptName("");
        //加盟企业
        mApprovalBean.setJoinCompanyName(qualityMemberBean.getCompanyName());
        mApprovalBean.setJoinCompanyNo(qualityMemberBean.getCompanyNo());
        mApprovalBean.setJoinCompanyType(qualityMemberBean.getServiceTypeName());
        mApprovalBean.setJoinCompanyProvice(qualityMemberBean.getProvinceNo());
        mApprovalBean.setJoinCompanyCity(qualityMemberBean.getCityNo());
        mApprovalBean.setJoinCompanyArea(qualityMemberBean.getDistrictNo());
        mApprovalBean.setJoinCompanyBusinessAddress(qualityMemberBean.getAddress());
    }

    // 初始化获取企业信息
    public void setMemberProfile(MemberProfileBean data) {
        String concat = getCustomText(data.getCurrentCompanyConstracts());
        String phone = getCustomText(data.getCurrentCompanyPhone());
        mBinding.tvTopContacts.setText(String.format("%s | %s", concat, phone));
        // 申请企业负责人
        mJoinEntity.setApplyCompanyContacts(concat);
        mJoinEntity.setApplyCompanyPhone(phone);
        mJoinEntity.setApplyCompanyBusinessOwner(data.getCurrentCompanyBusinessOwner()); // 负责人
        if (isAgainInvite) {
            // 获取邀请记录审批流程详情
            if (mBinding.approvalLayout.getVisibility() == View.VISIBLE && !TextUtils.isEmpty(qualityMemberBean.getProcessId())) {
                sModel.getProcessData(qualityMemberBean);
            } else {
                setInviteRecordDetail(null, mApprovalBean);
            }
        } else {
            setInviteRecordDetail(null, mApprovalBean);
        }
    }

    // 初始化获取企业审批信息
    public void setInviteRecordDetail(ProcessBean processBean, MemberApprovalBean data) {
        if (processBean != null) {
            mApprovalBean = data;
        }
        mBinding.itemApprovalCompany.setContent(mApprovalBean.getApplyCompanyName());
        mBinding.itemApprovalUser.setContent(mApprovalBean.getApplyUserName());
        mBinding.itemApprovalDepartment.setContent(mApprovalBean.getApplyDeptName());
        mBinding.cfkApproval.setEditContent(mApprovalBean.getDetail());
        // 再次邀请且流程id不为空时，获取流程信息
        if (isAgainInvite) {
            if (processBean != null) {
                setInviteRecordDetailAndNoApproval(data.getMemberLeagueJoinDTO());
            } else {
                sModel.getJoinEditDetail(qualityMemberBean);
            }
        } else {
            // 设置加盟信息
            setInviteRecordDetailAndNoApproval(mJoinEntity);
        }
    }

    // 初始化获取加盟企业信息
    public void setInviteRecordDetailAndNoApproval(MInviteEntity entity) {
        if (entity != null) {
            mJoinEntity = entity;
        }
        mBinding.itemRelation.setContent(TextUtils.equals("1", mJoinEntity.getRelation()) ? "供方会员" : "需方会员");
        mBinding.itemApplyCompany.setContent(mJoinEntity.getApplyCompanyName());
        mBinding.itemApplyUser.setContent(getCustomText(mJoinEntity.getApplyCompanyBusinessOwner()));
        mBinding.itemCompany.setContent(mJoinEntity.getCompanyName());
        mBinding.itemUser.setContent(mJoinEntity.getContacts());
        mBinding.itemLever.setContent(mJoinEntity.getLevel());
        mBinding.itemType.setContent(formatListToString(mJoinEntity.getAllCategoryName()));
        mBinding.itemCooperationExpected.setContent(mJoinEntity.getCooperationExpected());
        mBinding.itemMemberRequirements.setContent(mJoinEntity.getMembershipRequirements());
        mBinding.cfkNotes.setEditContent(mJoinEntity.getInvitationInstructions());
        mBinding.cfkBusiness.setEditContent(mJoinEntity.getCooperationBusiness());
        mBinding.itemContacts.setContent(mJoinEntity.getContacts());
        mBinding.itemContactsPhone.setContent(mJoinEntity.getPhone());
        List<ParamDtosEntity> paramDtos = mJoinEntity.getParamDtos();
        if (paramDtos != null && paramDtos.size() > 0) {
            List<AppendFieldsView.AppendField> appendFields = new ArrayList<>();
            for (ParamDtosEntity paramDto : paramDtos) {
                appendFields.add(new AppendFieldsView.AppendField(paramDto.title, paramDto.content));
            }
            mBinding.fieldsLayout.setData(appendFields);
        }
    }

    // 邀请加盟成功
    public void inviteSuccess() {
//        mBinding.containerLayout.setVisibility(View.GONE);
//        mBinding.successLayout.getRoot().setVisibility(View.VISIBLE);
//        EventBus.getDefault().postSticky(MenuEvent.make().setMessageTag(EventConstant.EVENT_MEMBER_APPROVAL_SUCCESS));
        if (isJumpFromWeb) {
            if (mBinding.approvalLayout.getVisibility() == View.VISIBLE) {
                MemberInviteOrApplyActivity.startInviteOrApplyApproval(this, 0);
            } else {
                MemberInviteOrApplyActivity.startInviteOrApplyRecord(this, 0);
            }
            setResult(RESULT_OK, new Intent());
        } else {
            Intent intent = new Intent();
            if (mBinding.approvalLayout.getVisibility() == View.VISIBLE) {
                intent.putExtra(MemberConfig.JUMP_RECORD_APPROVAL, true);
            } else {
                intent.putExtra(MemberConfig.JUMP_RECORD, true);
            }
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    // 发起审批成功
    public void approveSuccess(BaseEntity entity) {
        if ("0".equals(entity.getCode())) {
            MToast.showToast(this, "审批信息发送成功");
            // 跳转至页面用户中心-审批列表-我发起的
            MemberConfig.getInstance().startApprovalManager(this, 1);
            EventBus.getDefault().postSticky(MemberEvent.make()
                    .setMessageTag(EventConstant.EVENT_MEMBER_APPROVAL_SUCCESS)
                    .setMessageData(qualityMemberBean)
            );
            finish();
        } else {
            MToast.showToast(this, entity.getMsg());
        }
    }

    // 设置会员门槛信息
    public void getThresholdByMemberType(List<ThresholdParamBean> data) {
        mBinding.joinReqLayout.setVisibility(View.VISIBLE);
        mBinding.thresholdRecycler.setLayoutManager(new LinearLayoutManager(this));
        MemberJoinThresholdAdapter thresholdAdapter = new MemberJoinThresholdAdapter(this, data);
        mBinding.thresholdRecycler.setAdapter(thresholdAdapter);
        thresholdAdapter.setSimpleResult(new SimpleResult<UploadFileBean>() {
            @Override
            public void onResult(UploadFileBean uploadFileBean, Object... objects) {
                sModel.uploadSingleFile(uploadFileBean);
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setUploadFileUrl(UploadFileBean item) {
        MemberJoinThresholdAdapter adapter = (MemberJoinThresholdAdapter) mBinding.thresholdRecycler.getAdapter();
        if (adapter == null) return;
        adapter.addFileData(item);
        adapter.notifyDataSetChanged();
    }

    public void showEmptyView() {
        finish();
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.item_lever) {
            // 会员等级
            sModel.showMemberLeverPop(mBinding.itemLever, new SimpleResult<CommonPopEntity>() {
                @Override
                public void onResult(CommonPopEntity commonPopEntity, Object... objects) {
                    mJoinEntity.setLevel(commonPopEntity.getTypeName());
                }
            });
        } else if (id == R.id.item_relation) {
            sModel.showSupplyDemandPop(mBinding.itemRelation, new SimpleResult<CommonPopEntity>() {
                @Override
                public void onResult(CommonPopEntity commonPopEntity, Object... objects) {
                    // 设置供需关系
                    if (!TextUtils.equals(commonPopEntity.getNo(), mJoinEntity.getRelation())) {
                        memberTypes = new ArrayList<>();
                        mBinding.itemType.setContent("");
                        mBinding.itemType2.setContent("");
                        mBinding.joinReqLayout.setVisibility(View.GONE);
                        MemberJoinThresholdAdapter adapter = (MemberJoinThresholdAdapter) mBinding.thresholdRecycler.getAdapter();
                        if (adapter != null) {
                            adapter.clearDatas();
                        }
                    }
                    mJoinEntity.setRelation(commonPopEntity.getNo());
                }
            });
        } else if (id == R.id.item_type) {
            if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            //	供需关系 relation 1.供方会员 2.需方会员
            if (TextUtils.equals("供方会员", mBinding.itemRelation.getContent())) {
                // ascription 0 供方 1需方
                ChooseMemberTypeActivity.start(this, memberTypes, "0", MemberConfig.REQ_MEMBER_TYPE);
            } else {
                ChooseMemberTypeActivity.start(this, memberTypes, "1", MemberConfig.REQ_MEMBER_TYPE);
            }
        } else if (id == R.id.item_type2) { // 会员类型诉求
            if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            // ascription 0 供方 1需方
            // 会员关系取反
            String ascription = TextUtils.equals("供方会员", mBinding.itemRelation.getContent()) ? "1" : "0";
            sModel.getMemberTypeList(mBinding.activityBar.topLayout.getHeight(), ascription, mJoinEntity.getApplyCompanyNo(), new SimpleResult<CommonPopEntity>() {
                @Override
                public void onResult(CommonPopEntity entity, Object... objects) {
                    if (mBinding.itemType2.getContent().equals(entity.getTypeName())) {
                        return;
                    }
                    mAppealCateList.clear();
                    mAppealCateList.add(entity);
                    mBinding.itemType2.setContent(entity.getTypeName());
                    MemberJoinThresholdAdapter adapter = (MemberJoinThresholdAdapter) mBinding.thresholdRecycler.getAdapter();
                    if (adapter != null) {
                        adapter.clearDatas();
                    }
                    mBinding.joinReqLayout.setVisibility(View.GONE);
                    sModel.getThresholdByMemberType(mJoinEntity.getApplyCompanyNo(), ascription, objects);
                }
            });
        } else if (id == R.id.item_approval_department) {
            // 申请部门
            sModel.showDepttPop(mBinding.itemApprovalDepartment, new SimpleResult<CompanyDeptBean>() {
                @Override
                public void onResult(CompanyDeptBean companyDeptBean, Object... objects) {
                    mApprovalBean.setApplyDeptName(companyDeptBean.getName());
                    mApprovalBean.setApplyDeptNo(companyDeptBean.getId());
                }
            });
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onMultiClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_finish) {
            setResult(RESULT_OK, new Intent());
            finish();
        } else if (id == R.id.tv_record) {
            if (isJumpFromWeb && !TextUtils.isEmpty(mJoinEntity.getProcessId())) {
                MemberInviteOrApplyActivity.startInviteOrApplyApproval(this, 0);
                setResult(RESULT_OK, new Intent());
                finish();
                return;
            }
            Intent intent = new Intent();
            if (mBinding.approvalLayout.getVisibility() == View.VISIBLE) {
                intent.putExtra(MemberConfig.JUMP_RECORD_APPROVAL, true);
            } else {
                intent.putExtra(MemberConfig.JUMP_RECORD, true);
            }
            setResult(RESULT_OK, intent);
            finish();
        } else if (id == R.id.submit) {
            if (TextUtils.isEmpty(mBinding.itemLever.getContent())) {
                MToast.showToast(this, "请选择会员等级");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemRelation.getContent())) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemType.getContent())) {
                MToast.showToast(this, "请选择会员类型");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemType2.getContent())) {
                MToast.showToast(this, "请选择会员类型诉求");
                return;
            }
            if (TextUtils.isEmpty(mBinding.cfkNotes.getEditContent())) {
                MToast.showToast(this, "请输入邀请说明");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemContacts.getContent())) {
                MToast.showToast(this, "请输入联系人");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemContactsPhone.getContent())) {
                MToast.showToast(this, "请输入联系电话");
                return;
            }

            mJoinEntity.setCooperationBusiness(mBinding.cfkBusiness.getEditContent());    // 合作业务[v1.0.9]
            mJoinEntity.setCooperationExpected(mBinding.itemCooperationExpected.getContent());    // 合作预期[v1.0.9]
            mJoinEntity.setMembershipRequirements(mBinding.itemMemberRequirements.getContent());// 会费要求[v1.0.9]
            mJoinEntity.setContacts(mBinding.itemContacts.getContent());
            mJoinEntity.setPhone(mBinding.itemContactsPhone.getContent());
            mJoinEntity.setInvitationInstructions(mBinding.cfkNotes.getEditContent());
            List<AppendFieldsView.AppendField> data = mBinding.fieldsLayout.getData(); //用户联系名
            List<ParamDtosEntity> paramDtos = new ArrayList<>();
            if (data != null && data.size() > 0) {
                for (AppendFieldsView.AppendField datum : data) {
                    if (!TextUtils.isEmpty(datum.title) && !TextUtils.isEmpty(datum.content)) {
                        paramDtos.add(new ParamDtosEntity(datum.title, datum.content));
                    }
                }
            }
            mJoinEntity.setParamDtos(paramDtos);
            Map<String, List<CommonPopEntity>> typeMap = null;
            if (isAgainInvite) {
                if (memberTypes != null && memberTypes.size() > 0) {
                    typeMap = CopyUtils.memberTypeToJson(memberTypes);
                }
            } else {
                typeMap = CopyUtils.memberTypeToJson(memberTypes);
            }
            String itemTypeStr = mBinding.itemType.getContent();
            mJoinEntity.setAllCategoryName(Arrays.asList(itemTypeStr.split(",")));
            if (typeMap != null) {
                mJoinEntity.setFirstCategory(getCategoryNos(typeMap.get("firstCategory")));
                mJoinEntity.setSecondCategory(getCategoryNos(typeMap.get("secondCategory")));
                mJoinEntity.setThirdCategory(getCategoryNos(typeMap.get("thirdCategory")));
                mJoinEntity.setFourCategory(getCategoryNos(typeMap.get("fourCategory")));
                mJoinEntity.setFiveCategory(getCategoryNos(typeMap.get("fiveCategory")));
            }
            // 获取会员门槛数据
            if (mBinding.joinReqLayout.getVisibility() == View.VISIBLE) {
                Map<String, List<CommonPopEntity>> typeMap2 = CopyUtils.memberTypeToJson(mAppealCateList);
                String itemTypeStr2 = mBinding.itemType2.getContent();
                mJoinEntity.setAllAppealCategoryName(Arrays.asList(itemTypeStr2.split(",")));
                mJoinEntity.setAppealFirstCategory(getCategoryNos(typeMap2.get("firstCategory")));
                mJoinEntity.setAppealSecondCategory(getCategoryNos(typeMap2.get("secondCategory")));
                mJoinEntity.setAppealThirdCategory(getCategoryNos(typeMap2.get("thirdCategory")));
                MemberJoinThresholdAdapter adapter = (MemberJoinThresholdAdapter) mBinding.thresholdRecycler.getAdapter();
                if (adapter != null) {
                    List<ThresholdParamBean> thresholdParams = adapter.getThresholdParams();
                    if (thresholdParams == null) {
                        return;
                    }
                    mJoinEntity.setMemberThresholdParamDtos(thresholdParams);
                }
            } else {
                mJoinEntity.setMemberThresholdParamDtos(new ArrayList<>());
            }
            // 判断是否需要审批
            if (mBinding.approvalLayout.getVisibility() == View.VISIBLE) {
                if (TextUtils.isEmpty(mBinding.cfkApproval.getEditContent())) {
                    MToast.showToast(this, "请输入审批说明");
                    return;
                }
                mApprovalBean.setDetail(mBinding.cfkApproval.getEditContent());
                mApprovalBean.setMemberLeagueJoinDTO(mJoinEntity);
                sModel.sendApprove(mApprovalBean);
            } else {
                sModel.invitedCom(mJoinEntity);
            }
        }
    }

    // 获取会员类型no
    private List<String> getCategoryNos(List<CommonPopEntity> list) {
        List<String> strings = new ArrayList<>();
        if (list == null || list.size() == 0) {
            return strings;
        }
        for (CommonPopEntity popEntity : list) {
            strings.add(popEntity.getNo());
        }
        return strings;
    }

    private String getCustomText(String text) {
        if (StringUtil.isEmpty(text)) {
            return "暂无数据";
        }
        return text;
    }

    public static String formatListToString(List<String> str) {
        if (str == null || str.size() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String s : str) {
            sb.append(s).append(",");
        }
        return sb.substring(0, sb.length() - 1);
    }

    private void setCfkEditViewStyle(CfkEditView editView) {
        editView.getEditText().setTextColor(getResources().getColor(R.color.FF000000));
        editView.getEditText().setHintTextColor(getResources().getColor(R.color.C0C4CC));
        editView.getEditText().setMinHeight(DisplayUtil.dip2px(this, 150));
    }

    private List<CommonPopEntity> memberTypes;

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (intent == null) {
            LogUtil.d("TAG", "onActivityResult chooseFile data is null");
            return;
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case MemberConfig.REQ_MEMBER_TYPE:
                    memberTypes = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
                    if (memberTypes != null && memberTypes.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        for (CommonPopEntity memberType : memberTypes) {
                            sb.append(memberType.getTypeName()).append(",");
                        }
                        String str = sb.substring(0, sb.toString().length() - 1);
                        mBinding.itemType.setContent(str);
                    } else {
                        mBinding.itemType.setContent("");
                    }
                    break;
                case MemberConfig.REQ_FILE_CHOOSE: //选择文件返回
                    MemberJoinThresholdAdapter adapter = (MemberJoinThresholdAdapter) mBinding.thresholdRecycler.getAdapter();
                    if (adapter == null) return;
                    adapter.handleFileChoose(getActivity(), intent);
//                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }
}
